package com.jtpay.sdk.jtpay.utils;


import android.Manifest;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;

import com.jtpay.sdk.jtpay.easypermissions.EasyPermissions;

import java.io.Closeable;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class PayFileUtil {
    public static final int EOF = -1;
    private static final int DEFAULT_BUFFER_SIZE = 1024 * 4;
    public static final int REQUEST_STORGE = 0x1;
    public static void copyToFile(final InputStream source, final File destination) throws IOException {
        final FileOutputStream output = openOutputStream(destination);
        try {
            copy(source, output);
            output.close(); // don't swallow close Exception if copy completes normally
        } finally {
            closeQuietly(output);
        }
    }

    public static FileOutputStream openOutputStream(final File file) throws IOException {
        return openOutputStream(file, false);
    }

    public static FileOutputStream openOutputStream(final File file, final boolean append) throws IOException {
        if (file.exists()) {
            if (file.isDirectory()) {
                throw new IOException("File '" + file + "' exists but is a directory");
            }
            if (file.canWrite() == false) {
                throw new IOException("File '" + file + "' cannot be written to");
            }
        } else {
            final File parent = file.getParentFile();
            if (parent != null) {
                if (!parent.mkdirs() && !parent.isDirectory()) {
                    throw new IOException("Directory '" + parent + "' could not be created");
                }
            }
        }
        return new FileOutputStream(file, append);
    }

    public static int copy(final InputStream input, final OutputStream output) throws IOException {
        final long count = copyLarge(input, output);
        if (count > Integer.MAX_VALUE) {
            return -1;
        }
        return (int) count;
    }

    public static long copyLarge(final InputStream input, final OutputStream output)
            throws IOException {
        return copy(input, output, DEFAULT_BUFFER_SIZE);
    }

    public static long copy(final InputStream input, final OutputStream output, final int bufferSize)
            throws IOException {
        return copyLarge(input, output, new byte[bufferSize]);
    }

    public static long copyLarge(final InputStream input, final OutputStream output, final byte[] buffer)
            throws IOException {
        long count = 0;
        int n;
        while (EOF != (n = input.read(buffer))) {
            output.write(buffer, 0, n);
            count += n;
        }
        return count;
    }

    public static void closeQuietly(final OutputStream output) {
        closeQuietly((Closeable) output);
    }

    public static void closeQuietly(final Closeable closeable) {
        try {
            if (closeable != null) {
                closeable.close();
            }
        } catch (final IOException ioe) {
            // ignore
        }
    }


    private PayFileUtil() {
        throw new RuntimeException();
    }

    public static boolean hasSDCardPermission(Context context) {
        return EasyPermissions.hasPermissions(context, Manifest.permission.WRITE_EXTERNAL_STORAGE);
    }

    public static void requestSDCardPermission(Activity activity) {
        EasyPermissions.requestPermissions(activity, "请给予存储权限", REQUEST_STORGE, Manifest.permission.WRITE_EXTERNAL_STORAGE);
    }

    public static void deleteFile(Context context, File folder) {
        if (folder != null) {
            File[] files = folder.listFiles();
            if (null != files) {
                for (File temp : files) {
                    if (temp.isFile()) {
                        temp.delete();
//                        Environment.getExternalStorageDirectory() + File.separator + QRCODE_FOLDER_NAME + File.separator + fileName
                        deleteImage(context, temp.getAbsolutePath());
                    } else {
                        deleteFile(context, temp);
                    }
                }
            }
        }
    }

    public static void createFolder(File folder) {
        if (!folder.exists()) {
            folder.mkdirs();
        }
    }

    private static boolean deleteImage(Context context, String imgPath) {
        boolean result = false;
        Cursor cursor = null;
        try {
            ContentResolver resolver = context.getContentResolver();
            cursor = MediaStore.Images.Media.query(resolver, MediaStore.Images.Media.EXTERNAL_CONTENT_URI, new String[]{MediaStore.Images.Media._ID}, MediaStore.Images.Media.DATA + "=?",
                    new String[]{imgPath}, null);
            if (null != cursor && cursor.moveToFirst()) {
                long id = cursor.getLong(0);
                Uri contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                Uri uri = ContentUris.withAppendedId(contentUri, id);
                int count = context.getContentResolver().delete(uri, null, null);
                result = count == 1;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != cursor) {
                cursor.close();
            }
        }
        return result;
    }
}
